import NProgress from 'accessible-nprogress'; // progress bar
import 'accessible-nprogress/dist/accessible-nprogress.min.css'; // 页面顶部进度条
import { getWhiteList, haveRouterPermission } from './router-util';

/**
 * 注册路由守卫
 */
export function useRouterGuard(): void {
  NProgress.configure({ showSpinner: false });
  const userStore = useUserStore();
  const appStore = useAppStore();
  const whiteList = getWhiteList();
  // 前置守卫
  $router.beforeEach((to, _from, next) => {
    if (to.path === '/') {
      next(appStore.homeRoute);
    }

    const toFullPath = to.fullPath || '';
    if (import.meta.env.DEV) {
      if (to.path.toLowerCase() !== to.path) {
        console.warn(`${to.path}路径包含大写建议改为小写`);
      }
    }

    // 显示顶部进度条
    NProgress.start();
    // 设置title
    document.title = getPageTitle(to.meta?.title || '');
    // 是否在白名单内
    if (whiteList.includes(to.path)) {
      next(); // 在白名单内
    } else if (!userStore.loginStatus) {
      toFullPath.startsWith('/login') ? next() : next(`/login?redirect=${encodeURIComponent(toFullPath)}`); // 未登录
    } else {
      if (haveRouterPermission(to.path)) {
        // 判断是否有访问权限
        next();
      } else {
        next(`/err403`); // 无权限
      }
    }
  });

  // 后置守卫
  $router.afterEach(() => {
    NProgress.done();
  });

  // 版本更新后自动刷新
  $router.onError((error) => {
    console.error('error====', error);
    const isChunkLoadFailed = error.message.match(/Loading chunk (\d)+ failed/g);
    if (isChunkLoadFailed) {
      window.location.reload();
    }
  });
}

/**
 * 得到页面的标题
 */
export function getPageTitle(title: string) {
  if (title) {
    return `${title} - 袋鼠短剧`;
  }
  return `袋鼠短剧`;
}
